<template>
  <div class="gi_table_page">
    <GiTable
      row-key="serialNumber"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1200 }"
      :pagination="false"
      :summary="summaryData"
      @cell-click="cellRow"
      @refresh="search"
    >
      <template #top>
        <GiForm v-model="queryForm" search :columns="queryFormColumns" size="medium" @search="search" @reset="reset"></GiForm>
      </template>
      <template #toolbar-right>
        <a-button @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>
      <template #goodReviewRate="{ record }">
        <span>{{ `${toFixed2(record.goodReviewRate)}%` }}</span>
      </template>
      <template #badReviewRate="{ record }">
        <span>{{ `${toFixed2(record.badReviewRate)}%` }}</span>
      </template>
      <template #exposureToVisitRate="{ record }">
        <span>{{ `${toFixed2(record.exposureToVisitRate)}%` }}</span>
      </template>
      <template #visitToPurchaseRate="{ record }">
        <span>{{ `${toFixed2(record.visitToPurchaseRate)}%` }}</span>
      </template>

    </GiTable>
  </div>
</template>

<script setup lang="ts">
import { Message, type TableInstance } from '@arco-design/web-vue'
import { reactive, ref } from 'vue'
import { exportStorePerformanceSummary, fetchStorePerformanceSummary } from '@/apis/cakerun/storePerformanceSummary'
import { useDownload, useTable } from '@/hooks'
import type { ColumnItem } from '@/components/GiForm'
import { listAllBrand } from '@/apis/cakerun/brandAccount'

const brandInfo = ref<any[]>([])

function getLastWeekMonToSunByDate(dateStr: string) {
  const date = new Date(dateStr)
  // 0:周日, 1:周一, ..., 6:周六
  const day = date.getDay() || 7
  // 本周一
  const thisMonday = new Date(date)
  thisMonday.setDate(date.getDate() - day + 1)
  // 上周一
  const lastMonday = new Date(thisMonday)
  lastMonday.setDate(thisMonday.getDate() - 7)
  // 上周日
  const lastSunday = new Date(lastMonday)
  lastSunday.setDate(lastMonday.getDate() + 6)
  const format = (d: Date) => d.toISOString().slice(0, 10)
  return [format(lastMonday), format(lastSunday)]
}

const getBrandInfos = async () => {
  const res = await listAllBrand({ enable: true })
  brandInfo.value = res.data.map((item) => ({ label: item.brand, value: item.id }))
}
const todayStr = new Date().toISOString().slice(0, 10)
const [start, end] = getLastWeekMonToSunByDate(todayStr)
const [lastStart, lastEnd] = getLastWeekMonToSunByDate(start)

const queryForm = reactive({
  accountIds: [],
  shopIds: [],
  city: '',
  lastWeekStartDate: lastStart,
  lastWeekEndDate: lastEnd,
  thisWeekRange: [start, end],
  thisWeekStartDate: start,
  thisWeekEndDate: end,
  scoreDate1: lastEnd,
  scoreDate2: end,
})


const queryFormColumns: ColumnItem[] = [
  {
    type: 'select',
    label: '品牌',
    field: 'accountIds',
    props: {
      options: brandInfo,
      placeholder: '请选择品牌',
      multiple: true,
    },
  },
  {
    type: 'range-picker',
    label: '时间区间',
    field: 'thisWeekRange',
    props: {
      format: 'YYYY-MM-DD',
      onChange: (val) => {
        queryForm.thisWeekStartDate = val[0]
        queryForm.thisWeekEndDate = val[1]
        const [lastStart, lastEnd] = getLastWeekMonToSunByDate(val[0])
        queryForm.lastWeekStartDate = lastStart
        queryForm.lastWeekEndDate = lastEnd
        queryForm.scoreDate1 = lastEnd
        queryForm.scoreDate2 = val[1]
      },
    },
  },
]

const toFixed2 = (val) => (val !== undefined && val !== null && !isNaN(val) ? Number(val).toFixed(2) : '-')

// 表格字段
const columns: TableInstance['columns'] = [
  { title: '门店名称', dataIndex: 'shopName', width: 150, align: 'center' },
  { title: '上周核销数', dataIndex: 'lastWeekOrderCount', width: 120, align: 'center' },
  { title: '上周收益', dataIndex: 'lastWeekRevenue', width: 120, align: 'center' },
  { title: '本周核销数', dataIndex: 'thisWeekOrderCount', width: 120, align: 'center' },
  { title: '本周收益', dataIndex: 'thisWeekRevenue', width: 120, align: 'center' },
  { title: '上周评分', dataIndex: 'lastScore', width: 100, align: 'center' },
  { title: '本周评分', dataIndex: 'thisScore', width: 100, align: 'center' },
  { title: 'ROS分', dataIndex: 'rosScore', width: 100, align: 'center' },
  { title: '好评数量', dataIndex: 'goodReviewCount', width: 100, align: 'center' },
  { title: '中差评数量', dataIndex: 'badReviewCount', width: 120, align: 'center' },
  { title: '好评率', dataIndex: 'goodReviewRate', slotName: 'goodReviewRate', width: 100, align: 'center' },
  { title: '差评率', dataIndex: 'badReviewRate', slotName: 'badReviewRate', width: 100, align: 'center' },
  { title: '曝光人数', dataIndex: 'exposureCount', width: 100, align: 'center' },
  { title: '访问人数', dataIndex: 'visitCount', width: 100, align: 'center' },
  { title: '购买人数', dataIndex: 'purchaseCount', width: 100, align: 'center' },
  { title: '曝光-访问转化率', dataIndex: 'exposureToVisitRate', slotName: 'exposureToVisitRate', width: 160, align: 'center' },
  { title: '访问-购买转化率', dataIndex: 'visitToPurchaseRate', slotName: 'visitToPurchaseRate', width: 160, align: 'center' },
]

// 表格数据
const {
  tableData: dataList,
  loading,
  search,
  summary,
} = useTable(async () => {
  // 处理日期区间
  if (!queryForm.accountIds || queryForm.accountIds.length === 0) {
    await getBrandInfos()
    queryForm.accountIds = [brandInfo.value[0].value]
  }
  return fetchStorePerformanceSummary(queryForm)
}, { immediate: true, summary: [] })

const reset = () => search()

// eslint-disable-next-line no-empty-pattern
const summaryData = ({}) => {
  return summary.value
}

const cellRow = (record: any, column: any) => {
  const data = record[column.dataIndex]
  if (data) {
    navigator.clipboard.writeText(data.toString()).then(() => {
      Message.success('复制成功')
    })
  }
}

const onExport = () => {
  useDownload(() => {
    Message.info('文件正在下载中，请稍后.....')
    return exportStorePerformanceSummary(queryForm)
  })
}
</script>

<style scoped lang="scss">
:deep(.arco-table-td-content){
  cursor: pointer;
}
</style>
